package com.txtsqlclient.ui.factory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.txtsqlclient.domain.DataSourceFactory;
import com.txtsqlclient.domain.DataSourceType;
import com.txtsqlclient.ui.si.DataSourceSubInterface;
import com.txtsqlclient.ui.si.DatabaseInfoSubInterface;
import com.txtsqlclient.ui.si.ExitCommandSubInterface;
import com.txtsqlclient.ui.si.FileInfoSubInterface;
import com.txtsqlclient.ui.si.GenericCommandSubInterface;
import com.txtsqlclient.ui.si.QuerySubInterface;
import com.txtsqlclient.ui.si.SubInterface;

/**
 * @author spadda
 * 
 */
public class SubInterfaceFactory {

	private static SubInterfaceFactory instance;

	private final static Log LOGGER = LogFactory
			.getLog(SubInterfaceFactory.class);

	private static final String EXIT = "exit";

	protected SubInterfaceFactory() {
		// empty constructor to enforce access restrictions.
	}

	public static SubInterfaceFactory getInstance() {
		if (instance == null) {
			LOGGER
					.debug("Factory instance does not exist. Creating a new instance.");
			instance = new SubInterfaceFactory();
		}
		return instance;
	}

	public SubInterface getDataSourceSubInterface(final DataSourceType dsType) {
		SubInterface si = null;
		if (dsType == null) {
			si = new DataSourceSubInterface();
		} else if (DataSourceFactory.LEGAL_FILE_DATASOURCE_TYPES
				.contains(dsType)) {
			si = new FileInfoSubInterface();
		} else if (DataSourceFactory.LEGAL_DATABASE_TYPES.contains(dsType)) {
			// Not a Singleton as class level variables are used.
			si = new DatabaseInfoSubInterface();
		} else {
			throw new IllegalArgumentException("Given Data Source Type, :"
					+ dsType
					+ " is neither a valid Database nor a File Data Source.");
		}
		if (si != null) {
			LOGGER.debug("Created DataSourceSubInterface of type: "
					+ si.getClass() + " for the Data Source type given: "
					+ dsType);
		}
		return si;
	}

	public SubInterface getCommandSubInterface(final String command) {
		// TODO Singletons can be used if the 'process' method can be made
		// synchronized.
		SubInterface si = null;
		if (command == null) {
			si = new GenericCommandSubInterface();
		} else if (command.equalsIgnoreCase(EXIT)) {
			si = new ExitCommandSubInterface();
		} else {
			si = new QuerySubInterface();
		}
		LOGGER.debug("Created CommandSubInterface of type: " + si.getClass()
				+ " for the Command given: " + command);
		return si;
	}
}